/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * JIFUsuario.java
 *
 * Created on 25/07/2011, 14:54:21
 */
package apresentacao;

import java.beans.PropertyVetoException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.TableColumnModel;
import javax.xml.bind.ParseConversionEvent;
import modelo.Usuario;
import modelo.UsuarioTableModel;
import persistencia.UsuarioDAO;

/**
 *
 * @author Felipe
 */
public class JIFUsuario extends javax.swing.JInternalFrame {

    private UsuarioTableModel usuarioTableModel;
    private UsuarioDAO usuarioDAO;
    private boolean alterar;
    private int id;
    
    /** Creates new form JIFUsuario */
    public JIFUsuario() {
        id =0;
        usuarioDAO = new UsuarioDAO();
        usuarioTableModel = new UsuarioTableModel();
        alterar = false;
        initComponents();
        txtBusca.setFocusable(true);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        jTabbedPane1 = new javax.swing.JTabbedPane();
        pnlLista = new javax.swing.JPanel();
        pnlSuperior = new javax.swing.JPanel();
        pnlBusca = new javax.swing.JPanel();
        cbbBusca = new javax.swing.JComboBox();
        btnBuscar = new javax.swing.JButton();
        txtBusca = new javax.swing.JTextField();
        pnlJtb = new javax.swing.JPanel();
        jtbSuperior = new javax.swing.JToolBar();
        btnIncluir = new javax.swing.JButton();
        btnAlterar = new javax.swing.JButton();
        btnDuplicar = new javax.swing.JButton();
        btnRemover = new javax.swing.JButton();
        pnlSuperiorCentro = new javax.swing.JPanel();
        pnlSuperiorCentroDivisor = new javax.swing.JPanel();
        pnlSul = new javax.swing.JPanel();
        pnlLeste = new javax.swing.JPanel();
        pnlOeste = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        pnlCadBasico = new javax.swing.JPanel();
        pnlCamposCadastro = new javax.swing.JPanel();
        lblNome = new javax.swing.JLabel();
        lblLogin = new javax.swing.JLabel();
        lblSenha = new javax.swing.JLabel();
        lblTipo = new javax.swing.JLabel();
        txtNome = new javax.swing.JTextField();
        txtLogin = new javax.swing.JTextField();
        cbbTipo = new javax.swing.JComboBox();
        ptxtSenha = new javax.swing.JPasswordField();
        pnlBotoes = new javax.swing.JPanel();
        btnGravar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();

        setClosable(true);
        setIconifiable(true);
        setTitle("Cadastro de usuarios");

        jTabbedPane1.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jTabbedPane1FocusLost(evt);
            }
        });

        pnlLista.setLayout(new java.awt.BorderLayout());

        pnlSuperior.setMinimumSize(new java.awt.Dimension(364, 50));
        pnlSuperior.setPreferredSize(new java.awt.Dimension(613, 50));
        pnlSuperior.setLayout(new java.awt.BorderLayout());

        pnlBusca.setLayout(new javax.swing.BoxLayout(pnlBusca, javax.swing.BoxLayout.LINE_AXIS));

        cbbBusca.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Nome", "Login", "Tipo de usuário" }));
        cbbBusca.setMaximumSize(new java.awt.Dimension(200, 20));
        cbbBusca.setMinimumSize(new java.awt.Dimension(200, 20));
        cbbBusca.setPreferredSize(new java.awt.Dimension(200, 20));
        pnlBusca.add(cbbBusca);

        btnBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/i16x16/buscar2.png"))); // NOI18N
        btnBuscar.setMaximumSize(new java.awt.Dimension(30, 20));
        btnBuscar.setMinimumSize(new java.awt.Dimension(30, 20));
        btnBuscar.setOpaque(false);
        btnBuscar.setPreferredSize(new java.awt.Dimension(30, 20));
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });
        pnlBusca.add(btnBuscar);

        txtBusca.setMaximumSize(new java.awt.Dimension(200, 20));
        txtBusca.setMinimumSize(new java.awt.Dimension(200, 20));
        txtBusca.setPreferredSize(new java.awt.Dimension(200, 20));
        txtBusca.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtBuscaKeyPressed(evt);
            }
        });
        pnlBusca.add(txtBusca);

        pnlSuperior.add(pnlBusca, java.awt.BorderLayout.EAST);

        pnlJtb.setLayout(new java.awt.BorderLayout());

        jtbSuperior.setBorder(null);
        jtbSuperior.setFloatable(false);
        jtbSuperior.setRollover(true);
        jtbSuperior.setOpaque(false);

        btnIncluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/i16x16/inserir.png"))); // NOI18N
        btnIncluir.setToolTipText("Incluir registro");
        btnIncluir.setFocusable(false);
        btnIncluir.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnIncluir.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jtbSuperior, org.jdesktop.beansbinding.ELProperty.create("false"), btnIncluir, org.jdesktop.beansbinding.BeanProperty.create("borderPainted"));
        bindingGroup.addBinding(binding);

        btnIncluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnIncluirActionPerformed(evt);
            }
        });
        jtbSuperior.add(btnIncluir);

        btnAlterar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/i16x16/alterar.png"))); // NOI18N
        btnAlterar.setToolTipText("Alterar registro");
        btnAlterar.setFocusable(false);
        btnAlterar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnAlterar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jtbSuperior, org.jdesktop.beansbinding.ELProperty.create("false"), btnAlterar, org.jdesktop.beansbinding.BeanProperty.create("borderPainted"));
        bindingGroup.addBinding(binding);

        btnAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAlterarActionPerformed(evt);
            }
        });
        jtbSuperior.add(btnAlterar);

        btnDuplicar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/i16x16/duplicar2.png"))); // NOI18N
        btnDuplicar.setToolTipText("Duplicar registro");
        btnDuplicar.setFocusable(false);
        btnDuplicar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnDuplicar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jtbSuperior, org.jdesktop.beansbinding.ELProperty.create("false"), btnDuplicar, org.jdesktop.beansbinding.BeanProperty.create("borderPainted"));
        bindingGroup.addBinding(binding);

        btnDuplicar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDuplicarActionPerformed(evt);
            }
        });
        jtbSuperior.add(btnDuplicar);

        btnRemover.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/i16x16/remover.png"))); // NOI18N
        btnRemover.setToolTipText("Remover registro");
        btnRemover.setFocusable(false);
        btnRemover.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnRemover.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jtbSuperior, org.jdesktop.beansbinding.ELProperty.create("false"), btnRemover, org.jdesktop.beansbinding.BeanProperty.create("borderPainted"));
        bindingGroup.addBinding(binding);

        btnRemover.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemoverActionPerformed(evt);
            }
        });
        jtbSuperior.add(btnRemover);

        pnlJtb.add(jtbSuperior, java.awt.BorderLayout.CENTER);

        pnlSuperior.add(pnlJtb, java.awt.BorderLayout.WEST);

        pnlSuperiorCentro.setLayout(new javax.swing.BoxLayout(pnlSuperiorCentro, javax.swing.BoxLayout.LINE_AXIS));

        pnlSuperiorCentroDivisor.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        pnlSuperiorCentroDivisor.setMaximumSize(new java.awt.Dimension(1000, 20));
        pnlSuperiorCentroDivisor.setOpaque(false);
        pnlSuperiorCentroDivisor.setPreferredSize(new java.awt.Dimension(1000, 20));
        pnlSuperiorCentro.add(pnlSuperiorCentroDivisor);

        pnlSuperior.add(pnlSuperiorCentro, java.awt.BorderLayout.CENTER);

        pnlLista.add(pnlSuperior, java.awt.BorderLayout.PAGE_START);
        pnlLista.add(pnlSul, java.awt.BorderLayout.SOUTH);
        pnlLista.add(pnlLeste, java.awt.BorderLayout.LINE_END);
        pnlLista.add(pnlOeste, java.awt.BorderLayout.LINE_START);

        jTable1.setAutoCreateRowSorter(true);
        jTable1.setModel(getModelo());
        jTable1.setRowHeight(20);
        ajustarTamanhoColunas();
        jScrollPane1.setViewportView(jTable1);

        pnlLista.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        jTabbedPane1.addTab("Lista", pnlLista);

        pnlCadBasico.setLayout(new java.awt.BorderLayout());

        lblNome.setText("Nome");

        lblLogin.setText("Login");

        lblSenha.setText("Senha");

        lblTipo.setText("Tipo de usuário");

        txtNome.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                txtNomeCaretUpdate(evt);
            }
        });

        txtLogin.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                txtLoginCaretUpdate(evt);
            }
        });

        cbbTipo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "ADMINISTRADOR", "TECNICO", "USUÁRIO" }));
        cbbTipo.setName(""); // NOI18N

        ptxtSenha.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                ptxtSenhaCaretUpdate(evt);
            }
        });

        javax.swing.GroupLayout pnlCamposCadastroLayout = new javax.swing.GroupLayout(pnlCamposCadastro);
        pnlCamposCadastro.setLayout(pnlCamposCadastroLayout);
        pnlCamposCadastroLayout.setHorizontalGroup(
            pnlCamposCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlCamposCadastroLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlCamposCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblTipo, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(lblSenha, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(lblLogin, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(lblNome, javax.swing.GroupLayout.Alignment.TRAILING))
                .addGap(18, 18, 18)
                .addGroup(pnlCamposCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, 249, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cbbTipo, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(pnlCamposCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(ptxtSenha, javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(txtLogin, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 118, Short.MAX_VALUE)))
                .addContainerGap(306, Short.MAX_VALUE))
        );
        pnlCamposCadastroLayout.setVerticalGroup(
            pnlCamposCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlCamposCadastroLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlCamposCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblNome)
                    .addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlCamposCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblLogin)
                    .addComponent(txtLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlCamposCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblSenha)
                    .addComponent(ptxtSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlCamposCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblTipo)
                    .addComponent(cbbTipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(250, Short.MAX_VALUE))
        );

        pnlCadBasico.add(pnlCamposCadastro, java.awt.BorderLayout.WEST);

        pnlBotoes.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        btnGravar.setText("Gravar");
        btnGravar.setEnabled(false);
        btnGravar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGravarActionPerformed(evt);
            }
        });

        btnCancelar.setText("Cancelar");

        javax.swing.GroupLayout pnlBotoesLayout = new javax.swing.GroupLayout(pnlBotoes);
        pnlBotoes.setLayout(pnlBotoesLayout);
        pnlBotoesLayout.setHorizontalGroup(
            pnlBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlBotoesLayout.createSequentialGroup()
                .addContainerGap(478, Short.MAX_VALUE)
                .addComponent(btnGravar, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnCancelar)
                .addContainerGap())
        );
        pnlBotoesLayout.setVerticalGroup(
            pnlBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlBotoesLayout.createSequentialGroup()
                .addGroup(pnlBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCancelar)
                    .addComponent(btnGravar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pnlCadBasico.add(pnlBotoes, java.awt.BorderLayout.PAGE_END);

        jTabbedPane1.addTab("Informações básicas", pnlCadBasico);

        getContentPane().add(jTabbedPane1, java.awt.BorderLayout.CENTER);

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnGravarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGravarActionPerformed
        if (!isAlterar()) {
            gravarUsuario();
        } else {
            alterarUsuario();
        }       
        limparCampos();
    }//GEN-LAST:event_btnGravarActionPerformed

    private void txtNomeCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_txtNomeCaretUpdate
        liberarBtnGravar();
    }//GEN-LAST:event_txtNomeCaretUpdate

    private void txtLoginCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_txtLoginCaretUpdate
        liberarBtnGravar();
    }//GEN-LAST:event_txtLoginCaretUpdate

    private void ptxtSenhaCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_ptxtSenhaCaretUpdate
        liberarBtnGravar();
    }//GEN-LAST:event_ptxtSenhaCaretUpdate

    private void btnRemoverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoverActionPerformed
        int n = JOptionPane.showConfirmDialog(null,
                    "Esta operação não poderá ser desfeita!\nDeseja realmente excluir este registro?\n",
                    "Exclusão de registro",
                    JOptionPane.YES_NO_OPTION);
        if (n == JOptionPane.YES_OPTION) {
            removerUsuario();
        }                
    }//GEN-LAST:event_btnRemoverActionPerformed

    private void btnIncluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnIncluirActionPerformed
       jTabbedPane1.setSelectedIndex(1);
    }//GEN-LAST:event_btnIncluirActionPerformed

    private void jTabbedPane1FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTabbedPane1FocusLost
        if (jTabbedPane1.getSelectedIndex() != 1) {
            limparCampos();
        }
    }//GEN-LAST:event_jTabbedPane1FocusLost

    private void btnDuplicarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDuplicarActionPerformed
        duplicarUsuario();
    }//GEN-LAST:event_btnDuplicarActionPerformed

    private void btnAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAlterarActionPerformed
        popularCampos();
    }//GEN-LAST:event_btnAlterarActionPerformed

    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
        buscar();
    }//GEN-LAST:event_btnBuscarActionPerformed

    private void txtBuscaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtBuscaKeyPressed
         if (evt.getKeyCode() == evt.VK_ENTER) {                      
             buscar();
         }  
    }//GEN-LAST:event_txtBuscaKeyPressed
    
    private void buscar() {
        String entrada = txtBusca.getText();
        int flag = cbbBusca.getSelectedIndex();        
        if (!"".equals(entrada)) {
            switch (flag) {
                case 0: usuarioTableModel.atualizarModelo(usuarioDAO.pesquisarNome(txtBusca.getText()));
                        break;
                case 1: usuarioTableModel.atualizarModelo(usuarioDAO.pesquisarLogin(txtBusca.getText()));
                        break;
                case 2: usuarioTableModel.atualizarModelo(usuarioDAO.pesquisarTipo(txtBusca.getText()));
                        break;
            }
        } else {
            usuarioTableModel.limpar();
            usuarioTableModel.addListaDeUsuario(usuarioDAO.getLista());
        }
    }    
    
    private void limparCampos() {
        txtNome.setText("");
        txtLogin.setText("");
        ptxtSenha.setText("");
        cbbTipo.setSelectedIndex(0);
    }
    
    private void popularCampos() {
        Usuario usuario = usuarioTableModel.getUsuario(jTable1.getSelectedRow());
        txtNome.setText(usuario.getNome());
        txtLogin.setText(usuario.getLogin());
        ptxtSenha.setText(usuario.getSenha());
        cbbTipo.setSelectedItem(usuario.getTipo());
        setId(usuario.getId());
        setAlterar(true);
        jTabbedPane1.setSelectedIndex(1);
    }
          
    private void liberarBtnGravar() {
        if (
                (txtNome.getText().length() > 0 ) && 
                (txtLogin.getText().length() > 0) &&
                (ptxtSenha.getText().length() > 0)
            ) 
        {
            btnGravar.setEnabled(true);
        } else
        {
            btnGravar.setEnabled(false);
        }       
    }
    
    private void gravarUsuario() {
        String nome = txtNome.getText();
        String login = txtLogin.getText();
        String senha = new String (ptxtSenha.getPassword());
        String tipo = (String) cbbTipo.getSelectedItem();
        Usuario usuario = new Usuario(nome, login, senha, tipo);
        
        try {
                usuarioDAO.inserir(usuario);
                usuarioTableModel.addUsuario(usuario);
                JOptionPane.showMessageDialog(null, "Registro gravado com sucesso!");
                jTabbedPane1.setSelectedIndex(0);            
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "Erro ao gravar registro!");
            }        
        setAlterar(false);
    }
    
    
    private void duplicarUsuario() {
        Usuario usuario = usuarioTableModel.getUsuario(jTable1.getSelectedRow());
        usuarioDAO.duplicar(usuario);
        usuarioTableModel.addUsuario(usuario);        
    }
    
    private void alterarUsuario() {
        try {
            // Pega o objeto usuario persistido
            Usuario usuario = usuarioDAO.getUsuario(getId());            
            
            // Atualiza o objeto
            usuario.setNome(txtNome.getText());
            usuario.setLogin(txtLogin.getText());
            usuario.setSenha(ptxtSenha.getText());
            usuario.setTipo((String)cbbTipo.getSelectedItem());
            
            // Atualiza
            try {
                usuarioDAO.atualizar(usuario);
                usuarioTableModel.atualizarUsuario(usuario);
                setAlterar(false);
                setId(0);
                JOptionPane.showMessageDialog(null, "Registro alterado com sucesso!");                
            }
            catch (Exception e) {
                JOptionPane.showMessageDialog(null, "Erro ao alterar registro!");
            }
            jTabbedPane1.setSelectedIndex(0);
        }        
        catch (Exception e) { 
            JOptionPane.showMessageDialog(null, "Nenhum registro selecionado!");            
        }
    }
    
    private void removerUsuario() {
        Usuario usuario = usuarioTableModel.removeUsuario(jTable1.getSelectedRow());
        usuarioDAO.remover(usuario);
    }
    
    private UsuarioTableModel getModelo() {
        ArrayList<Usuario> alUsuario = usuarioDAO.getLista(); 
        usuarioTableModel = new UsuarioTableModel(alUsuario);        
        return usuarioTableModel;    
    }
    
    private void ajustarTamanhoColunas() {
        jTable1.getColumnModel().getColumn(0).setPreferredWidth(400);
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(120);
        jTable1.getColumnModel().getColumn(2).setPreferredWidth(120);
        jTable1.getColumnModel().getColumn(3).setPreferredWidth(400);
    }
    
    // Getters and setters
    private void setAlterar(boolean alterar) { this.alterar = alterar; }
    private boolean isAlterar() { return this.alterar; }
    private void setId(int id) { this.id = id; }
    private int getId() { return this.id; }
    
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAlterar;
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnDuplicar;
    private javax.swing.JButton btnGravar;
    private javax.swing.JButton btnIncluir;
    private javax.swing.JButton btnRemover;
    private javax.swing.JComboBox cbbBusca;
    private javax.swing.JComboBox cbbTipo;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JToolBar jtbSuperior;
    private javax.swing.JLabel lblLogin;
    private javax.swing.JLabel lblNome;
    private javax.swing.JLabel lblSenha;
    private javax.swing.JLabel lblTipo;
    private javax.swing.JPanel pnlBotoes;
    private javax.swing.JPanel pnlBusca;
    private javax.swing.JPanel pnlCadBasico;
    private javax.swing.JPanel pnlCamposCadastro;
    private javax.swing.JPanel pnlJtb;
    private javax.swing.JPanel pnlLeste;
    private javax.swing.JPanel pnlLista;
    private javax.swing.JPanel pnlOeste;
    private javax.swing.JPanel pnlSul;
    private javax.swing.JPanel pnlSuperior;
    private javax.swing.JPanel pnlSuperiorCentro;
    private javax.swing.JPanel pnlSuperiorCentroDivisor;
    private javax.swing.JPasswordField ptxtSenha;
    private javax.swing.JTextField txtBusca;
    private javax.swing.JTextField txtLogin;
    private javax.swing.JTextField txtNome;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
     
    
 }